
#ifndef __EV_COMM_H__
#define __EV_COMM_H__

#include <QObject>
#include <QThreadPool>
#include <QMetaObject>
#include <QMessageBox>
#include <QSerialPort>
#include "mainwindow.h"
#include "ev_serial.h"

class EvComm : public QObject
{
    Q_OBJECT

public:
    explicit EvComm(MainWindow *window, QObject *parent = nullptr);
    ~EvComm();

public slots:
    void onFirmwareUpgrade();
    void onDevReset();
    void onFirmwareRead();
    void onReadVersion();
    void onSendCommand();
    void onOpSerialPort();
    void onRefreshSerialPort();

private:
    MainWindow *m_window;
    QThreadPool *threadPool;
    EvSerial *m_serial;
    bool isProcessing;

private:
    template<typename T, typename ...Args> void onCommButtonHandler(Args &&...args);
};

template<typename T, typename ...Args>
void EvComm::onCommButtonHandler(Args &&...args)
{
    if (!m_serial->isOpen()) {
        QMessageBox::warning(m_window, "错误", "串口未打开!!!");
        return;
    }

    if (isProcessing) {
        QMessageBox::information(m_window, "提示", "操作正在进行中\n\n 请稍候...");
        return;
    }
    isProcessing = true;
    this->m_window->progressBar->setValue(0);
    m_window->statusBar()->showMessage("操作进行中...");
    T *task = new T(std::forward<Args>(args)...);
    connect(task, &T::progressUpdated, this,
        [this](int value){
            this->m_window->progressBar->setValue(value);
        }
    );
    connect(task, &T::messageLogged, this,
        [this](QString message){
            this->m_window->commandDisplay->append(message);
        }
    );
    connect(task, &T::finished, this,
        [this](bool success){
            if (success) {
                this->m_window->progressBar->setValue(100);
                this->m_window->statusBar()->showMessage("操作完成", 0);
            } else {
                this->m_window->statusBar()->showMessage("操作失败", 0);
            }
            isProcessing = false;
        }
    );
    threadPool->start(task);
}
#endif /* __EV_COMM_H__ */
